import {Button, useAppTheme, Text} from 'tsun-smart-ui';
import React, {Component, ReactElement, type ReactNode} from 'react';
import {useTranslation} from 'react-i18next';
import {View, StyleSheet} from 'react-native';
import Error from '@/assets/icon/error.svg';
class ErrorBoundary extends Component<
  {
    children: ReactNode;
    fallback?: (props: Parameters<typeof ErrorFallback>[0]) => ReactElement;
  },
  {
    hasError: boolean;
    error: null | {message: string};
  }
> {
  state = {
    hasError: false,
    error: null,
  };
  componentDidCatch(error: Error): void {
    this.setState({
      hasError: true,
      error: error,
    });
  }
  handleRefresh = () => {
    this.setState({
      hasError: false,
    });
  };
  render(): ReactNode {
    const {children, fallback} = this.props;
    return (
      <>
        {this.state.hasError ? (
          fallback ? (
            React.createElement(fallback, {
              error: this.state.error,
              onRefresh: this.handleRefresh,
            })
          ) : (
            <ErrorFallback
              error={this.state.error}
              onRefresh={this.handleRefresh}
            />
          )
        ) : (
          children
        )}
      </>
    );
  }
}
export default ErrorBoundary;
const ErrorFallback = ({
  error,
  onRefresh,
}: {
  error: Error | null;
  onRefresh: () => void;
}) => {
  const theme = useAppTheme();
  const {t} = useTranslation();
  return (
    <View
      style={[
        styles.container,
        {backgroundColor: theme.colors?.background?.primary},
      ]}>
      <View style={styles.content}>
        <Error width={45} height={48} />
        <Text
          className="  mt-3 mb-6"
          style={{
            color: theme.colors?.neutral?.tip,
          }}>
          {error?.message || '发生了一些错误'}
        </Text>
        <Button
          onPress={onRefresh}
          size="medium"
          title={t('common.reload')}
          icon={'refresh'}
          style={{
            borderColor: theme.colors?.brand?.primary,
          }}></Button>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  content: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 24,
  },
  title: {
    marginTop: 16,
    marginBottom: 8,
  },
  message: {
    textAlign: 'center',
    marginBottom: 24,
  },
  button: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 24,
    paddingVertical: 12,
    borderRadius: 8,
  },
  buttonText: {
    marginLeft: 8,
    fontSize: 16,
    fontWeight: '500',
  },
});
